<?php
// Server
class Server
{
    private $serv;

    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
            'worker_num' => 8,
            'daemonize' => false,
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'debug_mode'=> 1,
            'task_worker_num'=>8,
        ));

        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->on('Close', array($this, 'onClose'));

        $this->serv->start();
    }

    public function onStart( $serv ) {
        echo "Start\n";
    }

    public function onConnect( $serv, $fd, $from_id ) {
        $serv->send( $fd, "Hello {$fd}!" );
    }

    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
        echo "Get Message From Client {$fd}:{$data}\n";
        // send a task to task worker.
        echo "接收数据" . $data . "\n";  //客户端数据
        $data = trim($data);
        $param = [
            'fd' => $fd,
            'data' => $data
        ];
        $task_id = $serv->task(json_encode($param),0);
        $serv->send($fd, "分发任务，任务id为$task_id\n");
        echo "Continue Handle Worker\n";
    }

    public function onTask(swoole_server $serv, $task_id, $from_id, $data) {
        echo "Tasker进程接收到数据,tashk_id:".$task_id.PHP_EOL;
        echo "#{$serv->worker_id}\tonTask: [PID={$serv->worker_pid}]: task_id=$task_id, from_id=$from_id, param=".$data.".".PHP_EOL;
        $serv->finish($data);
    }

    public function onFinish(swoole_server $serv, $task_id, $data) {
        echo "Task#$task_id finished, param=".$data.PHP_EOL;
    }

    public function onClose( $serv, $fd, $from_id ) {
        echo "Client {$fd} close connection\n";
    }

}
// 启动服务器
$server = new Server();